package com.cls.business.controller;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.cls.business.entity.Notice;
import com.cls.business.entity.Topic;
import com.cls.business.entity.TopicPlan;
import com.cls.business.service.INoticeService;
import com.cls.business.service.ITopicPlanService;
import com.cls.business.service.ITopicService;
import com.cls.common.annotation.ControllerEndpoint;
import com.cls.common.controller.BaseController;
import com.cls.common.entity.MyConstant;
import com.cls.common.entity.QueryRequest;
import com.cls.common.entity.ResponseVO;
import com.cls.common.enums.DictEnum;
import com.cls.common.exception.MyException;
import com.cls.common.utils.MyUtil;
import com.cls.common.utils.StringUtils;
import com.cls.system.entity.SysDict;
import com.cls.system.service.ISysDictService;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课题 Controller
 *
 * @author wandering
 * @date 2020-11-12 17:34:30
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class TopicController extends BaseController {

    private final ITopicService topicService;

    private final ISysDictService sysDictService;

    private final ITopicPlanService topicPlanService;

    private final INoticeService noticeService;

    /**
     * 课题列表页面
     **/
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/topic/{planId}")
    public String topicIndex(@PathVariable Long planId, Model model) {
        //获取学科字典表
        List<SysDict> noticeType = sysDictService.findByParentCode(DictEnum.SUBJECT_TYPE.getCode());
        model.addAttribute("subjectType", noticeType);
        TopicPlan topicPlan = topicPlanService.getById(planId);
        model.addAttribute("planId", planId);
        model.addAttribute("isGenerateCode", topicPlan.getIsGenerateCode());
        model.addAttribute("year", topicPlan.getYear());
        return MyUtil.view("business/topic/topic");
    }

    /**
     * 课题新增页面
     *
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/topic/topicAdd/{planId}")
    public String topicAdd(@PathVariable Long planId, Model model) {
        model.addAttribute("planId", planId);
        //课题类型  年度 委托
        List<SysDict> byCode = sysDictService.findByParentCode(DictEnum.TOPIC_CLASSIFY.getCode());
        model.addAttribute("topicClassifyCode", byCode);
        //查询年度课题分类
        List<SysDict> annualType = sysDictService.findByParentCode(DictEnum.WTKTLB.getCode());
        model.addAttribute("annualType", annualType);
        //查询委托课题分类
        List<Map<String, Object>> group_list = sysDictService.selectByParentCode(DictEnum.TOPIC_LEVEL_TYPE.getCode());
        Map<String, Object> map = new HashMap<>();
        map.put("groups", group_list);
        model.addAllAttributes(map);
        return MyUtil.view("business/topic/topicAdd");
    }

    /**
     * 课题修改页面
     *
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/topic/topicUpdate/{topicId}")
    public String topicUpdate(@PathVariable Long topicId, Model model) {
        Topic topic = topicService.getById(topicId);

        if (org.apache.commons.lang3.StringUtils.isNotBlank(topic.getTopicLevelType())) {
            //查询字典父code
            String parentCode = sysDictService.selectForParentCode(topic.getTopicLevelType()).getCode();
            topic.setParentTopicLevelType(parentCode);
        }
        model.addAttribute("topic", topic);
        //课题类型  年度 委托
        List<SysDict> byCode = sysDictService.findByParentCode(DictEnum.TOPIC_CLASSIFY.getCode());
        model.addAttribute("topicClassifyCode", byCode);
        //查询年度课题分类
        List<SysDict> annualType = sysDictService.findByParentCode(DictEnum.WTKTLB.getCode());
        model.addAttribute("annualType", annualType);
        //查询课题分类
        List<Map<String, Object>> group_list = sysDictService.selectByParentCode(DictEnum.TOPIC_LEVEL_TYPE.getCode());
        Map<String, Object> map = new HashMap<>();
        map.put("groups", group_list);
        model.addAllAttributes(map);
        return MyUtil.view("business/topic/topicUpdate");
    }

    /**
     * 课题详情页面
     *
     * @return
     */
    @GetMapping(MyConstant.VIEW_PREFIX + "biz/topic/topicDetail/{topicId}")
    public String topicDetail(@PathVariable Long topicId, Model model) {
        Topic topic = topicService.getById(topicId);
        model.addAttribute("topic", topic);
        return MyUtil.view("business/topic/topicDetail");
    }

    /**
     * 指定topic该期对于的所有课题指南
     *
     * @return
     */
    @GetMapping("topic/{topicId}")
    public List<Topic> getTopicsByYear(@PathVariable Long topicId) {
        Topic topic = topicService.getById(topicId);
        Topic param = new Topic();
        param.setYear(topic.getYear());
        return topicService.getPublishedTopics(param);
    }

    /**
     * 课题申报时，指南筛查
     *
     * @return
     */
    @GetMapping("topics/declare")
    @ResponseBody
    public ResponseVO getTopicsByYear(String year, String topicClassifyCode) {
        if (StringUtils.isEmpty(topicClassifyCode) || year == null) {
            return ResponseVO.failure("参数异常！");
        }
        if (DictEnum.ANNUAL.getCode().equals(topicClassifyCode)) {
            TopicPlan topicPlan = topicPlanService.selectByPeriod(year);
            if (topicPlan == null) {
                return ResponseVO.failure("该期次没有选题！");
            }
            if (topicPlan.getApplyNoticeId() == null) {
                return ResponseVO.failure("申请通知公告未发布！");
            }
            Notice notice = noticeService.getById(topicPlan.getApplyNoticeId());
            if (notice == null) {
                return ResponseVO.failure("未找到通知公告！");
            }
            if (!notice.getIsPublish()) {
                return ResponseVO.failure("申请通知公告未发布！");
            }
        }
        Topic param = new Topic();
        param.setYear(year);
        param.setTopicClassifyCode(topicClassifyCode);
        return ResponseVO.success(topicService.getPublishedTopics(param));
    }


    @GetMapping("biz/topic/list")
    @ResponseBody
//    @RequiresPermissions("topic:list")
    public ResponseVO topicList(QueryRequest request, Topic topic) {
        //根据年份来查询所有的课题（包括年度和委托）
        PageInfo<Topic> pageInfo = this.topicService.findTopics(request, topic);
        return ResponseVO.success(pageInfo);
    }


    /**
     * 生成Topic编码
     *
     * @return
     */
    @ControllerEndpoint(operation = "生成Topic编码", exceptionMessage = "生成Topic编码失败")
    @PostMapping("biz/topic/createCode/{planId}/{year}")
    @ResponseBody
    @RequiresPermissions("topic:update")
    public ResponseVO createCode(@PathVariable Long planId, @PathVariable String year) {
        //判断申报公告是否发布，如果没有发布则不能生成编码。
        /*TopicPlan topicPlan = this.topicPlanService.getById(planId);
        Long applyNoticeId = topicPlan.getApplyNoticeId();
        if (applyNoticeId == null) {
            throw new MyException("请先创建申报公告！");
        }
        Notice notice = noticeService.getById(applyNoticeId);
        if (!notice.getIsPublish()) {
            throw new MyException("请先发布申报公告！");
        }*/
        try {
            topicService.createTopicCode(planId, year);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new MyException("对不起，编码生成失败！");
        }

        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "新增Topic", exceptionMessage = "新增Topic失败")
    @PostMapping("biz/topic/topicAdd")
    @ResponseBody
    @RequiresPermissions("topic:add")
    public ResponseVO addTopic(@Valid Topic topic) {
        this.topicService.createTopic(topic);
        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "多个删除Topic", exceptionMessage = "删除Topic失败")
    @PostMapping("biz/topic/deletes/{ids}")
    @ResponseBody
    @RequiresPermissions("topic:delete")
    public ResponseVO deleteTopics(@PathVariable String ids) {
        String[] idArry = ids.split(StringPool.COMMA);
        this.topicService.deleteTopics(idArry);
        return ResponseVO.success();
    }


    @ControllerEndpoint(operation = "删除单个Topic", exceptionMessage = "删除Topic失败")
    @PostMapping("biz/topic/delete/{topicId}")
    @ResponseBody
    @RequiresPermissions("topic:delete")
    public ResponseVO deleteTopic(@PathVariable Long topicId) {
        this.topicService.removeById(topicId);
        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "修改Topic", exceptionMessage = "修改Topic失败")
    @PostMapping("biz/topic/update")
    @ResponseBody
    @RequiresPermissions("topic:update")
    public ResponseVO updateTopic(Topic topic) {
        this.topicService.updateTopic(topic);
        return ResponseVO.success();
    }

    @ControllerEndpoint(operation = "导出Topic", exceptionMessage = "导出Excel失败")
    @GetMapping("biz/topic/word/{planId}")
    @RequiresPermissions("topic:list")
    public void export(@PathVariable Long planId, HttpServletResponse response) {
        this.topicService.download(planId, response);
    }

}
